package com.moody.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.calculator.RiskAppCalculator;
import com.moody.hibernate.domain.CodeLib;
import com.moody.hibernate.domain.CustInfo;
import com.moody.hibernate.domain.CustLimit;
import com.moody.hibernate.domain.DebtEc;
import com.moody.hibernate.domain.DebtInfo;
import com.moody.hibernate.domain.PriceRaroc;
import com.moody.hibernate.domain.ReportData;
import com.moody.hibernate.domain.ReportList;
import com.moody.init.DataDictionary;
import com.moody.init.DataLib;
import com.moody.init.ParamModelInit;
import com.moody.service.CustomerService;
import com.moody.service.ObligationService;
import com.moody.service.RatingService;
import com.moody.service.RiskAppService;
import com.moody.util.CalendarUtil;
import com.moody.util.FormatUtil;

/*
 * Copyright © Moody analytics
 *
 * @Author: Wang Fuqiang
 * @Time: 2011-12-24 下午13:43:35
 * @Modified by: Fuqiang Wang
 * @Description: 
 */

@Controller
@RequestMapping("/riskApp")
public class RiskAppContoller {
	private static final Logger log = LoggerFactory.getLogger(RiskAppContoller.class);
	WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	ServletContext context = web.getServletContext();  
	WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);
	
	@Resource
	private RiskAppService riskAppService;
	@Resource
	private CustomerService customerService;
	@Resource
	private ObligationService obligationService;
	@Resource
	private RatingService ratingService;
	
	@RequestMapping("/calculateCustLimit")
	public void calculateCustLimit(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String isSaveString = request.getParameter("isSave");
		boolean isSave = false;
		if(isSaveString != null && isSaveString.equals("1"))isSave = true;
		
		String custId = request.getSession().getAttribute("custLimitCustId").toString();
		CustLimit custLimit = riskAppService.findCustLimitByCustId(custId);
		
		//客户在本行的债务余额
		Double debtBalance = 0.0;
		if(request.getParameter("debtBalance") !=null)
			debtBalance = Double.valueOf(request.getParameter("debtBalance"));
		Double outGuaranty = 0.0;
		if(request.getParameter("outGuaranty")!=null)
			outGuaranty = Double.valueOf(request.getParameter("outGuaranty"));
		Double obbalance = 0.0;// 其他行的债务余额
		if(request.getParameter("obbalance")!=null)
			obbalance = Double.valueOf(request.getParameter("obbalance"));
		
		Double netAsset = this.getNaAndOb(custId).get("netAsset") - outGuaranty;
		
		custLimit.setNetAsset(netAsset);
		custLimit.setObbalance(obbalance);
		
		//杠杆倍数
		Double pdFactor = Double.valueOf(request.getParameter("pdfactor"));
		//偿债能力增长系数
		Double solventFactor = 1.0;
		String solventFactorName = request.getParameter("solventFactor");
		if(DataDictionary.getInstance().getDataDictionary().get("SolvencyParam").keySet().contains(solventFactorName)){
			String solventFactorString = DataDictionary.getInstance().getNameByCodeAndId("SolvencyParam", solventFactorName);
			solventFactor = Double.parseDouble(solventFactorString);
		}
		else{
			solventFactor = Double.parseDouble(solventFactorName);
		}
			
		//行业调整系数
		Double industryFactor = Double.valueOf(request.getParameter("industryFactor"));
		//区域调整系数
		
		Double regionFactor = 1.0;
		String regionFactorName = request.getParameter("regionFactor");
		if(DataDictionary.getInstance().getDataDictionary().get("AreaParam").keySet().contains(regionFactorName)){
			String regionFactorString = DataDictionary.getInstance().getNameByCodeAndId("AreaParam", regionFactorName);
			regionFactor = Double.parseDouble(regionFactorString);
		}
		else{
			regionFactor = Double.parseDouble(regionFactorName);
		}
		
		//初始限额
		Double initLimit = custLimit.getNetAsset()  * pdFactor * solventFactor * industryFactor * regionFactor - (custLimit.getObbalance()-debtBalance);
		BigDecimal bd = new BigDecimal(initLimit); 
	    BigDecimal bd1 = bd.setScale(2,bd.ROUND_HALF_UP); 
	    initLimit=bd1.doubleValue(); 
		
		if(initLimit < 0 )
			initLimit = 0.00;
		custLimit.setInitLimit(initLimit);
		custLimit.setPdfactor(pdFactor);
		custLimit.setSolventFactor(solventFactor);
		custLimit.setIndustryFactor(industryFactor);
		custLimit.setRegionFactor(regionFactor);
		
		//最终限额= MIN( 初始限额，客户级别限额，监管限额)
		Double pdLimit = 0.00;
		Double rLimit = 0.00;
		Double pd = 1.00;
		
		CustInfo custInfo = customerService.findCustByCustId(custId);
		
		List<CodeLib> limitList = ParamModelInit.getInstance().getLimitParams();
		for(CodeLib codeLib : limitList){
			if(CustLimit.PDPARAM.equals(codeLib.getId().getItemNo())){
				if(custInfo.getCreditLevel()!=null && !("").equals(custInfo.getCreditLevel())){
					List<CodeLib> codeLibList = ParamModelInit.getInstance().getLeverParams();
					for(CodeLib leverLimit : codeLibList){
						if(leverLimit.getId().getItemNo().equals(custInfo.getCreditLevel())){
							pd = Double.parseDouble(leverLimit.getItemName());
						}
					}
					if(!isZero(pd)){
						pdLimit = Double.parseDouble(codeLib.getItemName()) / pd * 100000000;
					}else{
						if(pdFactor!=null && !isZero(pdFactor)){
							pdLimit = Double.parseDouble(codeLib.getItemName()) / pdFactor * 100000000;
						}
					}
					
				}else{
					List<CodeLib> codeLibList = ParamModelInit.getInstance().getLeverParams();
					for(CodeLib leverLimit : codeLibList){
						if(leverLimit.getId().getItemNo().equals(custInfo.getCreditLevel())){
							pd = Double.parseDouble(leverLimit.getItemName());
						}
					}
					if(pdFactor!=null && !isZero(pdFactor)){
						pdLimit = Double.parseDouble(codeLib.getItemName()) / pdFactor * 100000000;
				}
			}
			}else if(CustLimit.RPARAM.equals(codeLib.getId().getItemNo())){
				rLimit = Double.parseDouble(codeLib.getItemName()) * 0.15 * 100000000;
			}
		}
		
		BigDecimal bd2 = new BigDecimal(pdLimit); 
	    BigDecimal bd3 = bd2.setScale(2,bd2.ROUND_HALF_UP); 
	    pdLimit=bd3.doubleValue(); 
		
	    BigDecimal bd4 = new BigDecimal(rLimit); 
	    BigDecimal bd5 = bd4.setScale(2,bd4.ROUND_HALF_UP); 
	    rLimit=bd5.doubleValue(); 
	    
		custLimit.setPdlimit(pdLimit);
		custLimit.setRlimit(rLimit);
		
		//最终限额= MIN( 初始限额，客户级别限额，监管限额)
		//我们是显示不为0最小的的数据
		Double finalLimit = initLimit;
		if(pdLimit < finalLimit && !isZero(pdLimit)){
			finalLimit = pdLimit;
		}
		if(rLimit < finalLimit && !isZero(rLimit)){
			finalLimit = rLimit;
		}
		
		custLimit.setFinalLimit(finalLimit);
		if(isSave)riskAppService.updateCustLimit(custLimit);
		
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", custLimit);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	
	}
	
	//判断double类型是否为0
	public Boolean isZero(Double data){
		if(data >10E-6 || data <-(10E-6))
			return false;
		else
			return true;
	}
	
	@RequestMapping("/getCustLimit")
	public void getCustLimit(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String custId = request.getSession().getAttribute("custLimitCustId").toString();
		CustLimit custLimit = riskAppService.findCustLimitByCustId(custId);
		Map<String,Double> dataMap = this.getNaAndOb(custId);
		
		Double netAsset = dataMap.get("netAsset");
		//其他行的债务余额 改为手工输入：
//		Double obbalance = dataMap.get("obalance");
		Double industryFactor = 0.0;
		Double pdFactor = 0.0;

		CustInfo custInfo = customerService.findCustByCustId(custId);
		
		//杠杆率：
		List<Map<String,String>> addTypeList =DataLib.getInstance().getListByType("IndustryParam");
		String industryType = custInfo.getIndustryType();
		if(industryType != null && !industryType.equals("")){
			for(Map map : addTypeList){
				if(industryType.startsWith(map.get("code").toString())){
					if(map.get("name") != null )industryFactor = Double.parseDouble(map.get("name").toString());
				}
			}
		}
		//客户评级杠杆系数：
		addTypeList =DataLib.getInstance().getListByType("LeverParam");
		String creditLevel = custInfo.getCreditLevel();
		if(creditLevel != null && !creditLevel.equals("")){
			for(Map map : addTypeList){
				if(map.get("code").equals(creditLevel)){
					if(map.get("name") != null )pdFactor = Double.parseDouble(map.get("name").toString());
				}
			}
		}
		
		if(custLimit==null){
			custLimit = new CustLimit();
			customerService.findRecentReport(custId);
			//取得该客户最近一期的年报数据			
			custLimit.setCustId(custId);
			custLimit.setNetAsset(netAsset);
//			custLimit.setObbalance(obbalance);
			custLimit.setIndustryFactor(industryFactor);
			custLimit.setPdfactor(pdFactor);
			custLimit.setCustName(custInfo.getCustName());
			riskAppService.insertCustLimit(custLimit);
		}else{
			custLimit.setNetAsset(netAsset);
//			custLimit.setObbalance(obbalance);
			custLimit.setIndustryFactor(industryFactor);
			custLimit.setPdfactor(pdFactor);
			custLimit.setSolventFactor(1.0);
			custLimit.setRegionFactor(1.0);
			riskAppService.updateCustLimit(custLimit);
		}
		double res = custLimit.getNetAsset();
		BigDecimal bd = new BigDecimal(res);
		res = bd.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
		custLimit.setNetAsset(res);
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", custLimit);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	}
	
	//获得净资产和他行债务余额
	public Map<String,Double> getNaAndOb(String custId){
		/*		
		//查找该客户的最新一期年报，查找其：有效净资产，有效净资产 = 帐面净资产 - 无形资产 - 递延资产 - 其他无效资产 - 或有负债
		//查找•	客户在其他行的债务余额，两种办法：
		//1.贷款总额（人行贷款查询系统）+ 应付债券（资产负债表）- 本行贷款余额
		//2. 短期借款 + 长期借款 + 一年内到期的长期借款 + 应付债券 - 客户本行的债务余额
		 */		
		//存在，则执行插入操作，否则执行更新操作
		
		Map<String,Double> map = customerService.findRecentReportByCustId(custId);
		
		CustInfo cust = customerService.findCustByCustId(custId);
		
		Double netAsset = 0.0;
		Double oblance = 0.0;
		String key = null;
		if(map.size() > 0) key =  map.keySet().toArray()[0].toString();
		
		if(key != null){
			if(key.charAt(0) == 'E' || key.substring(0, 2).equals("FR")){//企业报表
				//所有者权益合计
				Double ownersEquity = map.get("EBS069");
				//无形资产
				Double intangibleAsset = map.get("EBS035");
				//递延资产
				Double deferredAsset = map.get("EBS039");
//				//应收账款净额
//				Double netReceivable = map.get("EBS007");
				//短期借款
				Double shortLoan = map.get("EBS045");
				//长期借款
				Double longLoan = map.get("EBS061");
				//一年内到期的非流动负债
				Double oneYearLoan = map.get("EBS058");
				//应付债券
				Double payableBond = map.get("EBS063");
				//商誉
				Double reputation = map.get("EBS037");
				//开发支出
				Double developOutcome = map.get("EBS036");
				//长期待摊费用
				Double division = map.get("EBS038");
				
				netAsset = ownersEquity-intangibleAsset-deferredAsset-developOutcome - division;
				oblance = shortLoan+longLoan+oneYearLoan+payableBond;
			}
			else if(key.charAt(0) == 'S'){//小企业报表
				//所有者权益合计
				Double ownersEquity = map.get("SBS050");
				//无形资产
				Double intangibleAsset = map.get("SBS022");
				//递延资产
				Double deferredAsset = 0.0;
//				//应收账款净额
//				Double netReceivable = map.get("SBS005");
				//短期借款
				Double shortLoan = map.get("SBS027");
				//长期借款
				Double longLoan = map.get("SBS040");
				//一年内到期的非流动负债
				Double oneYearLoan = map.get("SBS037");
				//应付债券
				Double payableBond = 0.0;
				//商誉
				Double reputation = 0.0;
				//长期待摊费用
				Double division = map.get("SBS023");
				
				netAsset = ownersEquity-intangibleAsset-deferredAsset-reputation - division;
				oblance = shortLoan+longLoan+oneYearLoan+payableBond;
			}
			else if(key.charAt(0) == 'P'){//事业报表
				//短期借款
				Double shortLoan = 0.0;
				//长期借款
				Double longLoan = 0.0;
				//一年内到期的非流动负债
				Double oneYearLoan = 0.0;
				//应付债券
				Double payableBond = 0.0;
				
				netAsset = map.get("PBS050");
				oblance = shortLoan+longLoan+oneYearLoan+payableBond;
			}
			else if(key.charAt(0) == 'F'){//金融同业
				//所有者权益合计
				Double ownersEquity = map.get("FBS092");
				//无形资产
				Double intangibleAsset = map.get("FBS040");
				//递延资产
				Double deferredAsset = (map.get("FBS042") == null)? 0.0 :map.get("FBS042");
//				//应收账款净额
//				Double netReceivable = (map.get("FBS014") == null)? 0.0 :map.get("FBS014");
				//短期借款
				Double shortLoan = map.get("FBS048");
				//长期借款
				Double longLoan = map.get("FBS074");
				//一年内到期的非流动负债
				Double oneYearLoan = map.get("FBS069");
				//应付债券
				Double payableBond = map.get("FBS068") + map.get("FBS078");
				
				netAsset = ownersEquity-intangibleAsset-deferredAsset;
				oblance = shortLoan+longLoan+oneYearLoan+payableBond;
			}
		}
		
		Map<String,Double> resultMap = new HashMap<String,Double>();
		resultMap.put("netAsset", netAsset);
		resultMap.put("obalance", oblance);

		return resultMap;
	}
	
	@RequestMapping("/computeLimit")
	public String computeLimit(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String custId = request.getParameter("custId");
		request.getSession().removeAttribute("custLimitCustId");
		request.getSession().setAttribute("custLimitCustId", custId);	
		request.getSession().removeAttribute("custLimitCustName");
		request.getSession().setAttribute("custLimitCustName", customerService.findCustByCustId(custId).getCustName());
		request.getSession().removeAttribute("custInfo");
		request.getSession().setAttribute("custInfo", customerService.findCustByCustId(custId));
		
		return "risk_application/CustLimit";
	}
	
	@RequestMapping("/showDebtECList")
	public String showDebtECList(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String custId = request.getParameter("custId");
		request.getSession().removeAttribute("debtECCustId");
		request.getSession().setAttribute("debtECCustId", custId);	
		request.getSession().removeAttribute("debtECCustName");
		request.getSession().setAttribute("debtECCustName", customerService.findCustByCustId(custId).getCustName());
		request.getSession().removeAttribute("custInfo");
		request.getSession().setAttribute("custInfo", customerService.findCustByCustId(custId));
		
		return "risk_application/DebtEC_DebtList";
	}
	
	//列出该客户的历史评级信息
		@RequestMapping("/listDebt")
		public void listDebt(HttpServletRequest request,HttpServletResponse response) throws IOException{ 
			//评级的客户ID
			String ratingCustId = "";
			if(request.getSession().getAttribute("debtECCustId")!=null)
				ratingCustId = request.getSession().getAttribute("debtECCustId").toString();
			
			//找出该客户的所有债项信息
			List<DebtInfo> debtList = obligationService.findDebtByCustId(ratingCustId);
			
			//分页
			Integer start = Integer.parseInt(request.getParameter("start"));
			Integer limit = Integer.parseInt(request.getParameter("limit"));
			List<DebtInfo> pageList;
			if(debtList.size()>start+limit)
				pageList = debtList.subList(start, limit+start); 
			else
				pageList = debtList.subList(start,debtList.size());
			
			//将某些字段的code转化为name展示
			
			for(DebtInfo debtInfo : pageList){
				debtInfo.setBusinessKind(DataDictionary.getInstance().getNameByCodeAndId("BusinessKind", debtInfo.getBusinessKind()));
				debtInfo.setCurrency(DataDictionary.getInstance().getNameByCodeAndId("Currency", debtInfo.getCurrency()));
				//TODO　债项业务品种尚未给出
				//debtInfo.setDebtType(DataDictionary.getInstance().getNameByCodeAndId("DebtType", debtInfo.getDebtType()));
				debtInfo.setGuarantyKind(DataDictionary.getInstance().getNameByCodeAndId("GuarantyKind", debtInfo.getGuarantyKind()));
				debtInfo.setGroupLoanType(DataDictionary.getInstance().getNameByCodeAndId("YesNo", debtInfo.getGroupLoanType()));
				
				
				//将债项的经济资本测算信息展示
				DebtEc debtEC = riskAppService.findDebtECByDebtNo(debtInfo.getDebtNo());
				if(debtEC!=null && debtEC.getRwa()!=null)
					debtInfo.setRwa(debtEC.getRwa());
				if(debtEC!=null && debtEC.getEc()!=null)
					debtInfo.setEc(debtEC.getEc());
				if(debtEC!=null && debtEC.getEl()!=null)
					debtInfo.setEl(debtEC.getEl());
				if(debtEC!=null && debtEC.getRc()!=null)
					debtInfo.setRc(debtEC.getRc());
				
				//LGD百分比显示
				debtInfo.setLgd(debtInfo.getLgd() * 100);
				
				//从lGD表中获得余额
				//TODO 
			}
			
			
			//转化为JSON
			response.setContentType("application/json; charset=utf-8");  
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out = response.getWriter();
			Map<String, Object> myCustMap = new HashMap<String, Object>(3);
			myCustMap.put("total", debtList.size());
			myCustMap.put("resultData", pageList);
			JSONObject myCustJO=JSONObject.fromObject(myCustMap);
			out.print(myCustJO);
			
			log.info("JSON数据："+myCustJO);
	}
		
	@RequestMapping("/computeEC")
	public String computeEC(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String debtNo = request.getParameter("debtNo");
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		request.getSession().removeAttribute("ECDebtNo");
		request.getSession().setAttribute("ECDebtNo", debtNo);	
		request.getSession().removeAttribute("ECDebtId");
		request.getSession().setAttribute("ECDebtId", debt.getDebtId());	
		request.getSession().removeAttribute("ECDebtName");
		request.getSession().setAttribute("ECDebtName", debt.getDebtDesc());
			
		return "risk_application/DebtEC";
	}
	
	@RequestMapping("/getDebtEC")
	public void getDebtEC(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String debtNo = request.getSession().getAttribute("ECDebtNo").toString();
		String custId = request.getSession().getAttribute("debtECCustId").toString();
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		DebtEc debtEc = riskAppService.findDebtECByDebtNo(debtNo);
		Double pd = ratingService.findHistoryRatingPdH(custId).get(0).getConfirmPdvalue();
		
		if(debtEc!=null){
			debtEc.setLgd(debt.getLgd());
			debtEc.setDebtSum(debt.getDebtSum());
			debtEc.setDebtId(debt.getDebtId());
			if(pd==null){
				//TODO PD不存在时的处理情况
				pd = 100.0;
				debtEc.setPd(pd);
			}
			debtEc.setPd(pd);
			if(debt.getEad()==null){
				//TODO EAD = Balance + CCF( commitment – balance) 此公式不明白
				debt.setEad(1.0);
			}
			debtEc.setEad(debt.getEad());
			riskAppService.updateDebtEC(debtEc);
		}else{
			debtEc = new DebtEc();
			debtEc.setCustId(request.getSession().getAttribute("debtECCustId").toString());
			debtEc.setCustName(request.getSession().getAttribute("debtECCustName").toString());
			debtEc.setDebtNo(debtNo);
			debtEc.setDebtId(debt.getDebtId());
			debtEc.setDebtDesc(debt.getDebtDesc());
			debtEc.setDebtCurrency(debt.getCurrency());
			debtEc.setLgd(debt.getLgd());
			if(debt.getEad()==null){
				//TODO EAD = Balance + CCF( commitment – balance) 此公式不明白
				debt.setEad(1.0);
			}
			debtEc.setEad(debt.getEad());
			debtEc.setDebtSum(debt.getDebtSum());
			debtEc.setPd(pd);
			riskAppService.insertDebtEC(debtEc);
		}
		
		//lgd需百分比显示
		debtEc.setLgd(debtEc.getLgd() * 100);
		
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", debtEc);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	}
	
	@RequestMapping("/calculateDebtEC")
	public void calculateDebtEC(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String isDefault = request.getParameter("default");
		String beelString = request.getParameter("beel");
		String ftp = request.getParameter("ftp");
		String ocp = request.getParameter("ocp");
		String busiTax = request.getParameter("busiTax");
		String roc = request.getParameter("roc");
		String lendingRate = request.getParameter("lendingRate");
		String debtNo = request.getSession().getAttribute("ECDebtNo").toString();
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		CustInfo cust = customerService.findCustByCustId(debt.getCustId());
		DebtEc debtEc = riskAppService.findDebtECByDebtNo(debtNo);
		debtEc.setBeel(beelString == null? 0:Double.parseDouble(beelString));
		debtEc.setIsDefault(isDefault);
		
		double pd = debtEc.getPd()/100;

		Double el = debtEc.getLgd() * debtEc.getEad() * pd;
		double k = 1.0;
		double r = 1.0;
		
		if(isDefault != null && isDefault.equals("1")){//已违约风险暴露的风险加权资产的计量
			double beel = 0;
			if(beelString != null && (FormatUtil.isDouble(beelString)|| FormatUtil.isInteger(beelString))) beel = Double.parseDouble(beelString)/100;
			k = Math.max(0, debtEc.getLgd() - beel);
		}
		else{
			isDefault = "0";
			int expFlag = RiskAppCalculator.COMPANY_COMMON;//初始化为主权风险暴露
			String expString = cust.getExposureType();
			if(expString == null){
				
			}
			else if(expString.equals("主权风险暴露")){
				expFlag = RiskAppCalculator.SOVEREIGNTY;
			}
			else if(expString.contains("金融机构风险暴露")){
				expFlag = RiskAppCalculator.FINANCE;
			}
			else if(expString.contains("一般公司暴露风险暴露")){
				expFlag = RiskAppCalculator.COMPANY_COMMON;
			}
			else if(expString.contains("中小企业风险暴露")){
				expFlag = RiskAppCalculator.COMPANY_SMALL;
			}
			else if(expString.contains("个人住房抵押贷款")){
				expFlag = RiskAppCalculator.RETAIL_MORTGAGE;
			}
			else if(expString.contains("合格循环零售风险暴露")){
				expFlag = RiskAppCalculator.RETAIL_RECYCLE;
			}
			else if(expString.contains("其它零售风险暴露")){
				expFlag = RiskAppCalculator.RETAIL_OTHERS;
			}
			
			if(expFlag != RiskAppCalculator.COMPANY_SMALL) {
				r = RiskAppCalculator.calculateR(pd, expFlag);
				k = RiskAppCalculator.calculateK(debtEc.getLgd(), pd, expFlag);
			}
			else{
				double mainBusiIncome = 0.0;
				if(cust.getMainBusiIncome()!= null) mainBusiIncome = cust.getMainBusiIncome();
				if(mainBusiIncome < 0) mainBusiIncome = 0;
				r = RiskAppCalculator.calculateR(pd, expFlag, mainBusiIncome);
				k = RiskAppCalculator.calculateK(debtEc.getLgd(), pd, expFlag,mainBusiIncome);
			}
		}
		
		Double rwa = k * 12.5 * debtEc.getEad();
		Double rc = rwa * 0.08;
		Double ec = rwa * 0.08;
		
		DecimalFormat df = new DecimalFormat("##0.00");
		el = Double.parseDouble(df.format(el));
		rwa = Double.parseDouble(df.format(rwa));
		rc = Double.parseDouble(df.format(rc));
		ec = Double.parseDouble(df.format(ec));
		debtEc.setEl(el);
		debtEc.setR(r);
		debtEc.setK(k);
		debtEc.setRwa(rwa);
		debtEc.setRc(rc);
		debtEc.setEc(ec);
		
//		riskAppService.updateDebtEC(debtEc);
		
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", debtEc);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	
	}
	
	@RequestMapping("/saveDebtEC")
	public void saveDebtEC(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String isDefault = request.getParameter("default");
		String beelString = request.getParameter("beel");
		String ftp = request.getParameter("ftp");
		String ocp = request.getParameter("ocp");
		String busiTax = request.getParameter("busiTax");
		String roc = request.getParameter("roc");
		String lendingRate = request.getParameter("lendingRate");
		String debtNo = request.getSession().getAttribute("ECDebtNo").toString();
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		CustInfo cust = customerService.findCustByCustId(debt.getCustId());
		DebtEc debtEc = riskAppService.findDebtECByDebtNo(debtNo);
		debtEc.setBeel(beelString == null? 0:Double.parseDouble(beelString));
		debtEc.setIsDefault(isDefault);
		
		double pd = debtEc.getPd()/100;

		Double el = debtEc.getLgd() * debtEc.getEad() * pd;
		double k = 1.0;
		double r = 1.0;
		
		if(isDefault != null && isDefault.equals("1")){//已违约风险暴露的风险加权资产的计量
			double beel = 0;
			if(beelString != null && FormatUtil.isDouble(beelString)) beel = Double.parseDouble(beelString);
			k = Math.max(0, debtEc.getLgd() - beel);
		}
		else{
			isDefault = "0";
			int expFlag = RiskAppCalculator.COMPANY_COMMON;//初始化为主权风险暴露
			String expString = cust.getExposureType();
			if(expString == null){
				
			}
			else if(expString.equals("主权风险暴露")){
				expFlag = RiskAppCalculator.SOVEREIGNTY;
			}
			else if(expString.contains("金融机构风险暴露")){
				expFlag = RiskAppCalculator.FINANCE;
			}
			else if(expString.contains("一般公司暴露风险暴露")){
				expFlag = RiskAppCalculator.COMPANY_COMMON;
			}
			else if(expString.contains("中小企业风险暴露")){
				expFlag = RiskAppCalculator.COMPANY_SMALL;
			}
			else if(expString.contains("个人住房抵押贷款")){
				expFlag = RiskAppCalculator.RETAIL_MORTGAGE;
			}
			else if(expString.contains("合格循环零售风险暴露")){
				expFlag = RiskAppCalculator.RETAIL_RECYCLE;
			}
			else if(expString.contains("其它零售风险暴露")){
				expFlag = RiskAppCalculator.RETAIL_OTHERS;
			}
			
			if(expFlag != RiskAppCalculator.COMPANY_SMALL) {
				r = RiskAppCalculator.calculateR(pd, expFlag);
				k = RiskAppCalculator.calculateK(debtEc.getLgd(), pd, expFlag);
			}
			else{
				double mainBusiIncome = 0.0;
				if(cust.getMainBusiIncome()!= null) mainBusiIncome = cust.getMainBusiIncome();
				if(mainBusiIncome < 0) mainBusiIncome = 0;
				r = RiskAppCalculator.calculateR(pd, expFlag, mainBusiIncome);
				k = RiskAppCalculator.calculateK(debtEc.getLgd(), pd, expFlag,mainBusiIncome);
			}
		}
		
		Double rwa = k * 12.5 * debtEc.getEad();
		Double rc = rwa * 0.08;
		Double ec = rwa * 0.08;
		
		DecimalFormat df = new DecimalFormat("##0.00");
		el = Double.parseDouble(df.format(el));
		rwa = Double.parseDouble(df.format(rwa));
		rc = Double.parseDouble(df.format(rc));
		ec = Double.parseDouble(df.format(ec));
		debtEc.setEl(el);
		debtEc.setR(r);
		debtEc.setK(k);
		debtEc.setRwa(rwa);
		debtEc.setRc(rc);
		debtEc.setEc(ec);
		riskAppService.updateDebtEC(debtEc);
		
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", debtEc);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	
	}
	
	
	@RequestMapping("/showPriceRarocList")
	public String showPriceRarocList(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String custId = request.getParameter("custId");
		request.getSession().removeAttribute("priceRarocCustId");
		request.getSession().setAttribute("priceRarocCustId", custId);	
		request.getSession().removeAttribute("priceRarocCustName");
		request.getSession().setAttribute("priceRarocCustName", customerService.findCustByCustId(custId).getCustName());
		request.getSession().removeAttribute("custInfo");
		request.getSession().setAttribute("custInfo", customerService.findCustByCustId(custId));
		
		return "risk_application/PriceRaroc_DebtList";
	}
	
	//列出该客户的历史评级信息
	@RequestMapping("/listPriceRarocDebt")
	public void listPriceRarocDebt(HttpServletRequest request,HttpServletResponse response) throws IOException{ 
		//评级的客户ID
		String ratingCustId = "";
		if(request.getSession().getAttribute("priceRarocCustId")!=null)
			ratingCustId = request.getSession().getAttribute("priceRarocCustId").toString();
		
		//找出该客户的所有债项信息
		List<DebtInfo> debtList = obligationService.findDebtByCustId(ratingCustId);
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		List<DebtInfo> pageList;
		if(debtList.size()>start+limit)
			pageList = debtList.subList(start, limit+start); 
		else
			pageList = debtList.subList(start,debtList.size());
		
		//将某些字段的code转化为name展示
		
		for(DebtInfo debtInfo : pageList){
			debtInfo.setBusinessKind(DataDictionary.getInstance().getNameByCodeAndId("BusinessKind", debtInfo.getBusinessKind()));
			debtInfo.setCurrency(DataDictionary.getInstance().getNameByCodeAndId("Currency", debtInfo.getCurrency()));
			
			debtInfo.setDebtType(DataDictionary.getInstance().getNameByCodeAndId("DebtType", debtInfo.getDebtType()));
			debtInfo.setGuarantyKind(DataDictionary.getInstance().getNameByCodeAndId("GuarantyKind", debtInfo.getGuarantyKind()));
			debtInfo.setGroupLoanType(DataDictionary.getInstance().getNameByCodeAndId("YesNo", debtInfo.getGroupLoanType()));

			DecimalFormat df = new DecimalFormat("##0.00");
			
			//从lGD表中获得余额
			PriceRaroc priceRaroc = riskAppService.findPriceRarocByDebtNo(debtInfo.getDebtNo());
			DebtEc debtEC = riskAppService.findDebtECByDebtNo(debtInfo.getDebtNo());
			if(priceRaroc!=null && priceRaroc.getRaroc()!=null)
				debtInfo.setRaroc(Double.parseDouble(df.format(priceRaroc.getRaroc()*100)));
			if(priceRaroc!=null && priceRaroc.getRiskPrice() !=null)
				debtInfo.setRiskPrice(Double.parseDouble(df.format(priceRaroc.getRiskPrice() * 100)));
			if(debtEC!=null && debtEC.getRwa()!=null)
				debtInfo.setRwa(debtEC.getRwa());
			if(debtEC!=null && debtEC.getEc()!=null)
				debtInfo.setEc(debtEC.getEc());
			if(debtEC!=null && debtEC.getEl()!=null)
				debtInfo.setEl(debtEC.getEl());
			if(debtEC!=null && debtEC.getRc()!=null)
				debtInfo.setRc(debtEC.getRc());
			
			//LGD百分比显示
			debtInfo.setLgd(Double.parseDouble(df.format(debtInfo.getLgd() * 100)));
			
		}
		
		
		//转化为JSON
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", debtList.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		log.info("JSON数据："+myCustJO);
	}
	
	
	@RequestMapping("/computeRaroc")
	public String computeRaroc(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String debtNo = request.getParameter("debtNo");
		request.getSession().removeAttribute("rarocDebtNo");
		request.getSession().setAttribute("rarocDebtNo", debtNo);	
		request.getSession().removeAttribute("rarocDebtName");
		request.getSession().setAttribute("rarocDebtName", obligationService.findDebtInfoById(debtNo).getDebtDesc());
			
		return "risk_application/PriceRaroc";
	}
	
	@RequestMapping("/getPriceRaroc")
	public void getPriceRaroc(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String debtNo = request.getSession().getAttribute("rarocDebtNo").toString();
		String custId = request.getSession().getAttribute("priceRarocCustId").toString();
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		PriceRaroc priceRaroc = riskAppService.findPriceRarocByDebtNo(debtNo);
		DebtEc debtEC = riskAppService.findDebtECByDebtNo(debtNo);
		Double pd = ratingService.findHistoryRatingPdH(custId).get(0).getConfirmPdvalue();
		request.getSession().setAttribute("priceRarocDebtId",debt.getDebtId());
		request.getSession().setAttribute("priceRarocDebtDesc",debt.getDebtDesc());
		if(priceRaroc!=null){
			priceRaroc.setDebtId(debt.getDebtId());
			priceRaroc.setEc(debtEC.getEc());
			priceRaroc.setEl(debtEC.getEl());
			Double debtBalance = debt.getDebtBalance();
			log.info("debtBalance: "+debtBalance);
			priceRaroc.setDebtBalance(debtBalance);
			riskAppService.updatePriceRaroc(priceRaroc);
		}else{
			priceRaroc= new PriceRaroc();
			priceRaroc.setDebtId(debt.getDebtId());
			priceRaroc.setCustId(request.getSession().getAttribute("priceRarocCustId").toString());
			priceRaroc.setCustName(request.getSession().getAttribute("priceRarocCustName").toString());
			priceRaroc.setDebtNo(debtNo);
			priceRaroc.setDebtCurrency(debt.getCurrency());
			
			
			Double debtBalance = debt.getDebtBalance();
			log.info("debtBalance: "+debtBalance);
			priceRaroc.setDebtBalance(debtBalance);
			riskAppService.insertPriceRaroc(priceRaroc);
		}
		//百分比显示需要：
		DecimalFormat df = new DecimalFormat("##0.00");
		if(priceRaroc.getBusiTax()!=null)priceRaroc.setBusiTax(Double.parseDouble(df.format(priceRaroc.getBusiTax() * 100)));
		if(priceRaroc.getRoc()!=null)priceRaroc.setRoc(Double.parseDouble(df.format(priceRaroc.getRoc() * 100)));
		if(priceRaroc.getFinanceCost()!=null)priceRaroc.setFinanceCost(Double.parseDouble(df.format(priceRaroc.getFinanceCost() * 100)));
		if(priceRaroc.getDebtRate()!=null)priceRaroc.setDebtRate(Double.parseDouble(df.format(priceRaroc.getDebtRate() * 100)));
		if(priceRaroc.getOperateCost()!=null)priceRaroc.setOperateCost(Double.parseDouble(df.format(priceRaroc.getOperateCost() * 100)));
		if(priceRaroc.getRaroc()!=null)priceRaroc.setRaroc(Double.parseDouble(df.format(priceRaroc.getRaroc() * 100)));
		if(priceRaroc.getRiskPrice()!=null)priceRaroc.setRiskPrice(Double.parseDouble(df.format(priceRaroc.getRiskPrice() * 100)));
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", priceRaroc);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	}
	
	@RequestMapping("/calculatePriceRaroc")
	public void calculatePriceRaroc(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String debtNo = request.getSession().getAttribute("rarocDebtNo").toString();
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		DebtEc debtEc = riskAppService.findDebtECByDebtNo(debtNo);
		PriceRaroc priceRaroc = riskAppService.findPriceRarocByDebtNo(debtNo);

		Double el = Double.valueOf(request.getParameter("el"));
		Double financeCost = Double.valueOf(request.getParameter("financeCost"))/ 100;
		Double operateCost = Double.valueOf(request.getParameter("operateCost")) / 100;
		Double busiTax = Double.valueOf(request.getParameter("busiTax")) /100;
		Double roc = Double.valueOf(request.getParameter("roc"))/100;
		Double debtRate = Double.valueOf(request.getParameter("debtRate"))/100;
		
		double ead = debtEc.getEad();
		Double raroc = ead * (debtRate * (1-busiTax) - el /ead  - financeCost - operateCost) / debtEc.getEc();
		Double riskPrice = (roc * priceRaroc.getEc() + el + ead * operateCost + ead * financeCost)/(ead*(1-busiTax));
		
		
		priceRaroc.setFinanceCost(financeCost);
		priceRaroc.setOperateCost(operateCost);
		priceRaroc.setBusiTax(busiTax);
		priceRaroc.setRoc(roc);
		priceRaroc.setDebtRate(debtRate);
		priceRaroc.setRaroc(raroc);
		priceRaroc.setRiskPrice(riskPrice);
		priceRaroc.setUpdateDate(CalendarUtil.getCurrentDateStr());
//		riskAppService.updatePriceRaroc(priceRaroc);
		
		//百分比显示需要：
		DecimalFormat df = new DecimalFormat("##0.00");
		priceRaroc.setRaroc(Double.parseDouble(df.format(priceRaroc.getRaroc() * 100)));
		priceRaroc.setRiskPrice(Double.parseDouble(df.format(priceRaroc.getRiskPrice() * 100)));
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", priceRaroc);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	
	}
	
	@RequestMapping("/savePriceRaroc")
	public void savePriceRaroc(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String debtNo = request.getSession().getAttribute("rarocDebtNo").toString();
		DebtInfo debt = obligationService.findDebtInfoById(debtNo);
		DebtEc debtEc = riskAppService.findDebtECByDebtNo(debtNo);
		PriceRaroc priceRaroc = riskAppService.findPriceRarocByDebtNo(debtNo);

		Double el = Double.valueOf(request.getParameter("el"));
		Double financeCost = Double.valueOf(request.getParameter("financeCost"))/ 100;
		Double operateCost = Double.valueOf(request.getParameter("operateCost")) / 100;
		Double busiTax = Double.valueOf(request.getParameter("busiTax")) /100;
		Double roc = Double.valueOf(request.getParameter("roc"))/100;
		Double debtRate = Double.valueOf(request.getParameter("debtRate"))/100;
		
		double ead = debtEc.getEad();
		Double raroc = ead * (debtRate * (1-busiTax) - el /ead  - financeCost - operateCost) / priceRaroc.getEc();
		Double riskPrice = (roc * priceRaroc.getEc() + el + ead * operateCost + ead * financeCost)/(ead*(1-busiTax));
		
		
		priceRaroc.setFinanceCost(financeCost);
		priceRaroc.setOperateCost(operateCost);
		priceRaroc.setBusiTax(busiTax);
		priceRaroc.setRoc(roc);
		priceRaroc.setDebtRate(debtRate);
		priceRaroc.setRaroc(raroc);
		priceRaroc.setRiskPrice(riskPrice);
		priceRaroc.setUpdateDate(CalendarUtil.getCurrentDateStr());
		riskAppService.updatePriceRaroc(priceRaroc);
		
		//百分比显示需要：
		DecimalFormat df = new DecimalFormat("##0.00");
		priceRaroc.setRaroc(Double.parseDouble(df.format(priceRaroc.getRaroc() * 100)));
		priceRaroc.setRiskPrice(Double.parseDouble(df.format(priceRaroc.getRiskPrice() * 100)));
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", priceRaroc);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		log.info("JSON: "+pdJO);
	
	}
}
